[LeetCode] 102 - Binary Tree Level Order Traversal

題意

Level Order Traversal 二元樹。

解法

BFS。

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if ( !root ) return [];
let queue = [root];
let levels = [];
while( queue.length !== 0 ){
let length = queue.length;
levels.push([]);
for ( let i = 0; i < length; i ++ ){
let node = queue.shift();
levels[levels.length-1].push(node.val);
if ( node.left ) queue.push(node.left);
if ( node.right ) queue.push(node.right);
}
}
return levels;
};